package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.CommentMapper;
import cn.tedu.weibo.mapper.WeiboMapper;
import cn.tedu.weibo.pojo.dto.WeiboDto;
import cn.tedu.weibo.pojo.entity.Weibo;
import cn.tedu.weibo.pojo.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/weibo")
public class WeiboController {
    @Autowired
    WeiboMapper mapper;

    //处理发送微博请求
    @RequestMapping("/insert")
    public int insert(@RequestBody WeiboDto weiboDto, HttpSession session) {
        System.out.println("weiboDto = " + weiboDto); //进行打桩输出测试
        UserVo user = (UserVo) session.getAttribute("user"); //得到当前登录的用户对象
        if (user == null) {
            return 2; //代表未登录
        }
        Weibo weibo = new Weibo(); //往数据库里面存的时候需要使用entity
        BeanUtils.copyProperties(weiboDto, weibo); //把weiboDto里面的数据装进weibo
        //给weibo对象的其它属性赋值
        weibo.setUserId(user.getId()); //设置当前登录的用户id为微博的作者id
        weibo.setCreated(new Date()); //设置当前时间为发布微博的时间
        System.out.println("weibo = " + weibo); //进行打桩输出测试
        mapper.insert(weibo);
        return 1; //代表发布完成
    }

    //处理首页的微博列表请求
    @RequestMapping("/select")
    public List<WeiboIndexVo> select() {
        return mapper.select();
    }

    //处理查看微博详情页面请求
    @RequestMapping("/selectById")
    public WeiboDetailVo selectById(int id) {
        return mapper.selectById(id);
    }

    //处理我的微博详情的请求
    @RequestMapping("/select/mine")
    public ResultVo selectMine(HttpSession session) {
        UserVo user = (UserVo) session.getAttribute("user");
        if (user == null) {
            return new ResultVo(2, "用户未登录", null);
        }
        //如果没有发过微博响应的会是一个空集合,客户端接收到之后也是一个空字符串
        return new ResultVo(1, "请求成功", mapper.selectMine(user.getId()));
    }

    @Autowired
    CommentMapper commentMapper;

    //处理删除微博及评论的请求
    @RequestMapping("/delete")
    public void delete(int id) {
        commentMapper.deleteByWeiboId(id); //删除相关评论
        mapper.deleteById(id); //删除微博
    }
}
